package com.koujun.meinv.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class StringUtils {
	
	public static String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
	}

	public static boolean isEmpty(CharSequence cs) {
		return cs == null || cs.length() == 0;
	}

	public static boolean isNotEmpty(CharSequence cs) {
		return !StringUtils.isEmpty(cs);
	}

	/**
	 * <p>
	 * Checks if a CharSequence is whitespace, empty ("") or null.
	 * </p>
	 * 
	 * <pre>
	 * StringUtils.isBlank(null)      = true
	 * StringUtils.isBlank("")        = true
	 * StringUtils.isBlank(" ")       = true
	 * StringUtils.isBlank("bob")     = false
	 * StringUtils.isBlank("  bob  ") = false
	 * </pre>
	 * 
	 * @param cs
	 *            the CharSequence to check, may be null
	 * @return {@code true} if the CharSequence is null, empty or whitespace
	 * @since 2.0
	 * @since 3.0 Changed signature from isBlank(String) to
	 *        isBlank(CharSequence)
	 */
	public static boolean isBlank(CharSequence cs) {
		int strLen;
		if (cs == null || (strLen = cs.length()) == 0) {
			return true;
		}
		for (int i = 0; i < strLen; i++) {
			if (Character.isWhitespace(cs.charAt(i)) == false) {
				return false;
			}
		}
		return true;
	}

	public static String trim(String str) {
		return str == null ? null : str.trim();
	}

	/**
	 * <p>
	 * Strips whitespace from the start and end of a String.
	 * </p>
	 * 
	 * <p>
	 * This is similar to {@link #trim(String)} but removes whitespace.
	 * Whitespace is defined by {@link Character#isWhitespace(char)}.
	 * </p>
	 * 
	 * <p>
	 * A {@code null} input String returns {@code null}.
	 * </p>
	 * 
	 * <pre>
	 * StringUtils.strip(null)     = null
	 * StringUtils.strip("")       = ""
	 * StringUtils.strip("   ")    = ""
	 * StringUtils.strip("abc")    = "abc"
	 * StringUtils.strip("  abc")  = "abc"
	 * StringUtils.strip("abc  ")  = "abc"
	 * StringUtils.strip(" abc ")  = "abc"
	 * StringUtils.strip(" ab c ") = "ab c"
	 * </pre>
	 * 
	 * @param str
	 *            the String to remove whitespace from, may be null
	 * @return the stripped String, {@code null} if null String input
	 */
	public static String strip(String str) {
		return strip(str, null);
	}

	public static String strip(String str, String stripChars) {
		if (isEmpty(str)) {
			return str;
		}
		str = stripStart(str, stripChars);
		return stripEnd(str, stripChars);
	}

	public static String stripStart(String str, String stripChars) {
		int strLen;
		if (str == null || (strLen = str.length()) == 0) {
			return str;
		}
		int start = 0;
		if (stripChars == null) {
			while (start != strLen && Character.isWhitespace(str.charAt(start))) {
				start++;
			}
		} else if (stripChars.length() == 0) {
			return str;
		} else {
			while (start != strLen && stripChars.indexOf(str.charAt(start)) != -1) {
				start++;
			}
		}
		return str.substring(start);
	}

	public static String stripEnd(String str, String stripChars) {
		int end;
		if (str == null || (end = str.length()) == 0) {
			return str;
		}

		if (stripChars == null) {
			while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) {
				end--;
			}
		} else if (stripChars.length() == 0) {
			return str;
		} else {
			while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != -1) {
				end--;
			}
		}
		return str.substring(0, end);
	}

	public static String toCSVString(Object obj) throws IllegalArgumentException, IllegalAccessException {
		StringBuffer buffer = null;
		Field[] fields = obj.getClass().getDeclaredFields();
		Object value = null;
		for (Field field : fields) {
			if (buffer == null) {
				buffer = new StringBuffer();
			} else {
				buffer.append(',');
			}
			if (field.isAccessible() == false) {
				field.setAccessible(true);
			}
			value = field.get(obj);
			buffer.append(field.getName()).append("=").append(String.valueOf(value));
		}
		return buffer == null ? "" : buffer.toString();
	}

	public static Map<String, String> splitToMap(String str, String delim) throws IllegalStateException {
		if (delim.length() != 2) {
			throw new IllegalStateException("delim must be 2 characters!");
		}
		char delim0 = delim.charAt(0);
		char delim1 = delim.charAt(1);
		Map<String, String> map = new HashMap<String, String>();
		String[] split0 = str.split(String.valueOf(delim0));
		for (String entry : split0) {
			int index = entry.indexOf(delim1);
			if (index > -1) {
				map.put(entry.substring(0, index), entry.substring(index + 1));
			}
		}
		return map;
	}

	public static String join(String[] array, String delim) {
		StringBuffer builder = new StringBuffer();
		for (String str : array) {
			builder.append(str).append(delim);
		}
		return builder.toString();
	}

	public static String getMIMETypeByExtName(String filePro) {
		String mimeType = "text/plain";

		if (filePro == null)
			return mimeType;
		if (filePro.toLowerCase().equals("doc")) {
			mimeType = "application/msword";
		} else if (filePro.toLowerCase().equals("ppt")) {
			mimeType = "application/mspowerpoint";
		} else if (filePro.toLowerCase().equals("xls")) {
			mimeType = "application/msexcel";
		} else if (filePro.toLowerCase().equals("vsd")) {
			mimeType = "application/msvisio";
		} else if (filePro.toLowerCase().equals("pdf")) {
			mimeType = "application/pdf";
		} else if (filePro.toLowerCase().equals("zip")) {
			mimeType = "application/zip";
		} else if ((filePro.toLowerCase().equals("jpg")) | (filePro.toLowerCase().equals("jpeg"))) {
			mimeType = "image/jpeg";
		} else if (filePro.toLowerCase().equals("gif")) {
			mimeType = "image/gif";
		} else if (filePro.toLowerCase().equals("tif")) {
			mimeType = "image/tiff";
		} else if (filePro.toLowerCase().equals("png")) {
			mimeType = "image/png";
		} else if (filePro.toLowerCase().equals("txt")) {
			mimeType = "text/plain";
		} else if (filePro.toLowerCase().equals("rtf")) {
			mimeType = "text/rtf";
		} else if (filePro.toLowerCase().equals("html")) {
			mimeType = "text/html";
		} else if (filePro.toLowerCase().equals("xml")) {
			mimeType = "text/xml";
		} else if (filePro.toLowerCase().equals("swf")) {
			mimeType = "application/x-shockwave-flash";
		} else {
			mimeType = "text/plain";
		}
		return mimeType;
	}

	public static <K, V> String map2String(Map<K, V> map) {
		if (map == null)
			return "";
		if (map.isEmpty())
			return "{}";

		StringBuffer result = new StringBuffer();
		for (Map.Entry<K, V> entry : map.entrySet()) {
			result.append(String.format(", %s -> %s ", entry.getKey().toString(), entry.getValue().toString()));
		}
		return "{" + result.substring(1) + "}";
	}

	public static String getUUID2() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString().replace("-", "");
	}

	public static String requestURLAsString(String httpURL) throws IOException {
		return requestURLAsString(httpURL, "UTF-8");
	}

	public static String requestURLAsString(String httpURL, String encoding) throws IOException {
		URL url = new URL(httpURL);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		String contents = getStreamContents(connection.getInputStream());
		connection.disconnect();
		return contents;
	}

	/**
	 * Returns the stream contents as an UTF-8 encoded string
	 * 
	 * @param is
	 *            input stream
	 * @return string contents
	 */
	public static String getStreamContents(InputStream is) {
		return getStreamContents(is, "UTF-8");
	}

	public static String getStreamContents(InputStream is, String encoding) {
		try {
			final char[] buffer = new char[0x10000];
			StringBuffer out = new StringBuffer();
			Reader in = new InputStreamReader(is, encoding);
			int read;
			do {
				read = in.read(buffer, 0, buffer.length);
				if (read > 0) {
					out.append(buffer, 0, read);
				}
			} while (read >= 0);
			in.close();
			return out.toString();
		} catch (IOException ioe) {
			throw new IllegalStateException("Error while reading response body", ioe);
		}
	}
}
